<template>
  <div class="device-container">
    <el-card shadow="hover" class="device-card">
      <template #header>
        <div class="header-container">
          <h3>设备管理</h3>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="openAddDeviceDialog">添加设备</el-button>
          </div>
        </div>
      </template>
      
      <div class="filter-container">
        <el-form :inline="true" :model="filterForm">
          <el-form-item label="设备名称">
            <el-input v-model="filterForm.deviceName" placeholder="请输入设备名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="设备状态">
            <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="在线" value="online"></el-option>
              <el-option label="离线" value="offline"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">查询</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
        <el-table :data="deviceList" border stripe style="width: 100%">
        <el-table-column prop="deviceName" label="设备名称" width="150">
          <template #default="scope">
            {{ scope.row.deviceName || scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column prop="deviceLocation" label="安装位置" width="200">
          <template #default="scope">
            {{ scope.row.deviceLocation || scope.row.location }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="设备状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'online' ? 'success' : 'danger'">
              {{ scope.row.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 添加设备对话框 -->
    <el-dialog
      v-model="addDeviceDialogVisible"
      title="添加设备"
      width="500px"
      append-to-body
    >
      <el-form :model="deviceForm" label-width="100px">
        <el-form-item label="设备名称">
          <el-input v-model="deviceForm.deviceName" placeholder="请输入设备名称"></el-input>
        </el-form-item>
        <el-form-item label="安装位置">
          <el-input v-model="deviceForm.deviceLocation" placeholder="请输入安装位置"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDeviceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDeviceForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { getAllDevices, addDevice, deleteDevice } from '../../api/device';
// 不再需要导入未使用的函数
// import { setUseMockData } from '../../api/mockData';

export default {
  name: 'DeviceList',
  setup() {
    // 筛选表单
    const filterForm = reactive({
      deviceName: '',
      status: ''
    });
    
    // 设备列表数据
    const deviceList = ref([]);
    const total = ref(0);
    const pageSize = ref(10);
    const currentPage = ref(1);
    const loading = ref(false);
    
    // 添加设备对话框
    const addDeviceDialogVisible = ref(false);
    const deviceForm = reactive({
      deviceName: '',
      deviceLocation: ''
    });
    
    // 获取状态对应的类型
    const getStatusType = (status) => {
      switch (status) {
        case 'online':
          return 'success';
        case 'offline':
          return 'danger';
        default:
          return '';
      }
    };      // 获取设备列表数据
    const fetchDevices = async () => {
      loading.value = true;      try {        // 始终先获取模拟数据
        const { devices } = await import('../../api/mockData.fixed'); 
        const mockDevices = devices;
          
        // 强制使用模拟数据 - 确保localStorage中设置了标识
        if (!localStorage.getItem('useMockData')) {
          localStorage.setItem('useMockData', 'true'); 
        }
          // 优先使用模拟数据
        if (mockDevices && mockDevices.devices) {
          deviceList.value = mockDevices.devices; 
          total.value = mockDevices.total;
        } else {
          console.error('模拟数据格式不正确:', mockDevices);
          deviceList.value = [];
          total.value = 0;
        }
        
        // 仅当明确禁用模拟数据时尝试API请求
        if (localStorage?.getItem('useMockData') !== 'true') {
          // 构建查询参数
          const params = {
            page: currentPage.value,
            size: pageSize.value,
            deviceName: filterForm.deviceName,
            status: filterForm.status
          };
          
          const response = await getAllDevices(params);
          
          if (response && response.data && response.data.devices) {
            deviceList.value = response.data.devices;
            total.value = response.data.total;      } else {            // API返回的数据格式不正确或为空，回退到模拟数据
            console.warn('API返回的设备数据格式不正确，使用备用数据');
            const { devices } = await import('../../api/mockData.fixed');            deviceList.value = devices.devices;
            total.value = devices.total;
          }
        }
      } catch (error) {
        console.error('获取设备列表失败:', error);
        // 出错时使用模拟数据
        try {
          const { devices } = await import('../../api/mockData.fixed');
          if (devices && devices.devices) {
            deviceList.value = devices.devices;
            total.value = devices.total;
          } else {
            console.error('备用数据格式不正确:', devices);
            deviceList.value = [];
            total.value = 0;
          }
        } catch (mockError) {
          console.error('加载备用数据也失败:', mockError);
          ElMessage.error('获取设备列表失败，请稍后再试');
        }
      } finally {
        loading.value = false;
      }
    };
    
    // 查询
    const handleFilter = () => {
      currentPage.value = 1;
      fetchDevices();
    };
    
    // 重置筛选表单
    const resetFilter = () => {
      filterForm.deviceName = '';
      filterForm.status = '';
      currentPage.value = 1;
      fetchDevices();
    };
    
    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size;
      fetchDevices();
    };
    
    const handleCurrentChange = (page) => {
      currentPage.value = page;
      fetchDevices();
    };
    
    // 打开添加设备对话框
    const openAddDeviceDialog = () => {
      deviceForm.deviceName = '';
      deviceForm.deviceLocation = '';
      addDeviceDialogVisible.value = true;
    };
    
    // 提交设备表单
    const submitDeviceForm = async () => {
      // 表单验证逻辑
      if (!deviceForm.deviceName || !deviceForm.deviceLocation) {
        ElMessage.warning('请填写完整信息');
        return;
      }
      
      const loadingInstance = ElLoading.service({
        target: '.device-container',
        text: '正在添加设备...'
      });
      
      try {
        // 调用API添加设备
        await addDevice(deviceForm);
        
        ElMessage.success('添加设备成功');
        addDeviceDialogVisible.value = false;
        
        // 重新获取设备列表
        fetchDevices();
      } catch (error) {
        console.error('添加设备失败:', error);
        ElMessage.error('添加设备失败，请稍后再试');
      } finally {
        loadingInstance.close();
      }
    };
    
    // 查看设备
    const handleView = (row) => {
      // 可以跳转到设备详情页或者打开详情弹窗
      ElMessage.info(`查看设备：${row.deviceName}`);
    };
    
    // 编辑设备
    const handleEdit = (row) => {
      // 打开编辑弹窗，填充现有数据
      deviceForm.deviceName = row.deviceName;
      deviceForm.deviceLocation = row.deviceLocation;
      
      // 可以使用一个标志来区分是添加还是编辑操作
      // 此处简化处理，仅显示消息
      ElMessage.info(`编辑设备：${row.deviceName}`);
    };
    
    // 删除设备
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除设备 ${row.deviceName} 吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        const loadingInstance = ElLoading.service({
          target: '.device-container',
          text: '正在删除...'
        });
        
        try {
          // 调用API删除设备
          await deleteDevice(row.id || row.deviceCode);
          ElMessage.success('删除成功');
          
          // 重新获取设备列表
          fetchDevices();
        } catch (error) {
          console.error('删除设备失败:', error);
          ElMessage.error('删除设备失败，请稍后再试');
        } finally {
          loadingInstance.close();
        }
      }).catch(() => {
        // 用户取消删除操作
      });
    };
      // 组件挂载后获取数据
    onMounted(() => {      // 强制启用模拟数据模式用于调试
      localStorage.setItem('useMockData', 'true');
      
      // 获取设备列表
      fetchDevices();
    });
    
    return {
      filterForm,
      deviceList,
      total,
      pageSize,
      currentPage,
      loading,
      addDeviceDialogVisible,
      deviceForm,
      getStatusType,
      handleFilter,
      resetFilter,
      handleSizeChange,
      handleCurrentChange,
      openAddDeviceDialog,
      submitDeviceForm,
      handleView,
      handleEdit,
      handleDelete
    };
  }
};
</script>

<style scoped>
.device-container {
  padding: 10px;
}

.device-card {
  width: 100%;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
